const fs = require("fs")
const path = require("path")
const { dbQuery } = require('../model/model.js')
const controller = {}


controller.loginpage = (req, res) => {
    if (req.session.userInfo) {
        res.redirect('/index')
    } else {
        res.render('login.html')
    }

}


controller.login = (req, res) => {
    let { username, password } = req.body;

    let sql = `select * from user_table where username='${username}' and password='${password}'`

    dbQuery(sql, (err, rows) => {

        if (rows.length) {
            let id = rows[0].user_id;

            req.session.userInfo = JSON.stringify({ id });
            res.redirect('/index')
        } else {
            console.log("错了");
            res.redirect('/')
        }

    })


}

// 退出登录
controller.loginOut = (req, res) => {

    let { id, denlu_item } = req.query;
    let sql = `update user_table set denlu_item=${denlu_item} where id= ${id}`

    dbQuery(sql, (err, rows) => {

        // 直接把session清空,达到退出登录效果
        req.session.userInfo = '';

        res.redirect('/')
    })

}

controller.registerPage = (req, res) => {

    res.render('register.html')

}


controller.register = (req, res) => {
    let { username, password } = req.body;

    let sql = `insert into user_table(username,password) values ("${username}","${password}")`

    dbQuery(sql, (err, rows) => {

    })

}


// 校验cookie中间件
controller.check = (req, res, next) => {
    if (req.session.userInfo) {
        next()
        // 为true就把执行权交给下一个
    }
    else {
        // 否则打回登录页面
        res.redirect('/')
    }
}


// 主页数据
controller.index = (req, res) => {
    let userId = JSON.parse(req.session.userInfo)
    // let sql = `select * from article`
    let sql = `select * from article full join user_table on user_table.user_id = ${userId.id}`
    dbQuery(sql, (err, rows) => {

        // 从cookie解析后拿来的id
        let id = userId.id;
        let username = rows[0].username
        let password = rows[0].password
        let avatar = rows[0].avatar;
        let denlu_item = rows[0].denlu_item;

        req.session.userInfo = JSON.stringify({ id, username, password, avatar, denlu_item });

        let user = JSON.parse(req.session.userInfo)
        res.render('index.html', { result: rows, user })

    })

}
// 主页数据
controller.list = (req, res) => {
   
    let sql = `select * from article`
    dbQuery(sql, (err, rows) => {
        res.render('list.html', { result: rows })

    })

}


controller.mimagai = (req, res) => {
    let user = JSON.parse(req.session.userInfo)
    let { password } = req.body
    let sql = `update user_table set password='${password}' where id =${user.id}`

    dbQuery(sql, (err, rows) => {
        //    后续应该修sscion里的密码
    })

}


// 分类页面
controller.categoryPage = (req, res) => {

    let user = JSON.parse(req.session.userInfo)
    res.render('category.html', { user })

}

//分类数据
controller.category = (req, res) => {
    let { cat_id } = req.query;
    let sql = `select * from article where cat_id=${cat_id}`
    let user = JSON.parse(req.session.userInfo)
    dbQuery(sql, (err, rows) => {
        res.render('list.html', { result: rows, user })
    })

}


// 删除
controller.delete = (req, res) => {
    let { id, img } = req.body;
    let sql = `delete from article where id=${id}`
    dbQuery(sql, (err, rows) => {

        if (img) {
            console.log("有");
            let oldpath = path.join(__dirname, '../', img)

            fs.unlink(oldpath, (err) => {
                console.log("删除成功");
                // console.log(err);
            })

        }
        res.redirect('/')
    })

}

// 添加的页面
controller.zhen = (req, res) => {
    let user = JSON.parse(req.session.userInfo)
    res.render('zhen.html', { user })
}



// 添加的路由
controller.upload = (req, res) => {

    let imgpath = ''
    let { originalname, filename } = req.file;
    let { title, author, content, toExamine, cat_id, time } = req.body;
    let ext = originalname.substring(originalname.indexOf('.')); // .png
    // 把上传成功后的文件进行重命名
    let oldPath = path.join(__dirname, '../', 'uploads', filename);
    let newPath = path.join(__dirname, '../', 'uploads', filename) + ext;

    fs.renameSync(oldPath, newPath)
    imgpath = `uploads/${filename}${ext}`

    let sql = `insert into article(title,img,author,content,status,cat_id,time) values ('${title}','${imgpath}','${author}','${content}',${toExamine},${cat_id},'${time}')`

    dbQuery(sql, (err, rows) => {
      
    })

}



controller.avatar = (req, res) => {

    let user = JSON.parse(req.session.userInfo)
    let imgpath = ''

    let { originalname, filename } = req.file;
    let ext = originalname.substring(originalname.indexOf('.')); // .png

    // 把上传成功后的文件进行重命名
    let oldPath = path.join(__dirname, '../', 'uploads', filename);
    let newPath = path.join(__dirname, '../', 'uploads', filename) + ext;

    fs.renameSync(oldPath, newPath)
    imgpath = `uploads/${filename}${ext}`

    let sql = `update user_table set avatar='${imgpath}' where user_id =${user.id}`
    dbQuery(sql, (err, rows) => {
        
      res.redirect('/')

    })

}


// 详情
controller.cha = (req, res) => {
    let { chaid } = req.query;
    let sql = `select * from article where id=${chaid} `

    dbQuery(sql, (err, rows) => {

        res.render('cha.html', { result: rows })

    })
}


// 修改的页面
controller.gai = (req, res) => {

    let { gaiid } = req.query;
    let sql = `select * from article where id = ${gaiid}`
    dbQuery(sql, (err, rows) => {
        res.render('gai.html', { result: rows })
    })
}


// 修改传数据的路由
controller.gaichen = (req, res) => {
    var imgpath = ''

    let { title, img, author, content, status, cat_id, time, gaiid } = req.body;
    // 如果req.file不为空,也就是有图片上传过来,就执行
    if (!req.file == '') {
        let { originalname, filename } = req.file;

        let ext = originalname.substring(originalname.indexOf('.')); // .png

        let oldPath = path.join(__dirname, '../', 'uploads', filename);
        let newPath = path.join(__dirname, '../', 'uploads', filename) + ext;
        // 添加文件到uploads
        fs.renameSync(oldPath, newPath)
        // 删除原来的文件
        fs.unlink(img, (err) => {
            console.log("删除成功");
        })
        imgpath = `uploads/${filename}${ext}`
    } else {
        // 没有删除图片就把原来图片的路径赋值给imgpath
        imgpath = img
    }

    let sql = `update article set title='${title}',img='${imgpath}',author='${author}',content='${content}',status='${status}',cat_id='${cat_id}',time='${time}' where id= ${gaiid};`

    dbQuery(sql, (err, rows) => {
        // console.log(err);
        // console.log(rows);
        res.redirect('/')
    })
}



module.exports = controller;